﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Eoffice.Models;

namespace Eoffice.Controllers
{
    public class NhanVienController : Controller
    {
        private EofficeDb db = new EofficeDb();

        //
        // GET: /NhanVien/
        #region[Index]
        public ActionResult Index(string searchTerm = null)
        {
            //var nvs = db.NVs.Include(n => n.PHONGBAN);
            //return View(nvs.ToList());

            if (true)
            {
                string page = "1"; //so phan trang hien tai
                var pagesize = 10; //so ban ghi tren 1 trang
                var numOfNews = 0; //tong so ban ghi co duoc truoc khi phan trang
                int curpage = 0; // trang hien tai dung cho phan trang
                if (Request["page"] != null)
                {
                    page = Request["page"];
                    curpage = Convert.ToInt32(page) - 1;
                }
                var all = db.NVs.ToList();
                var pages = all.Skip(curpage * pagesize).Take(pagesize).ToList();

                //var pages = data.sp_Brands_Phantrang(page, productize, "", "").ToList();
                var url = Request.Path;
                numOfNews = all.Count;

                if (numOfNews > 0)
                {
                    ViewBag.Pager = Phantrang.PhanTrang(pagesize, curpage, numOfNews, url);
                }
                else
                {
                    ViewBag.Pager = "";
                }
                return View(pages);
            }
        }
        #endregion


        //
        // GET: /NhanVien/Create

        #region[Create]
        public ActionResult Create()
        {
            ViewBag.MAPB = new SelectList(db.PHONGBANs, "MAPB", "TENPB");
            return View();
        }
        #endregion

        //
        // POST: /NhanVien/Create
        #region[Create]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection form, NV nhanvien)
        {
            ViewBag.MAPB = new SelectList(db.PHONGBANs, "MAPB", "TENPB", nhanvien.MAPB);

            if(ModelState.IsValid)
            {
                string name = ToFirstUpper(form["HOTENNV"]);

                nhanvien.MSNV = form["MSNV"].ToString();
                nhanvien.HOTENNV = name;
                nhanvien.NGAYSINH = form["NGAYSINH"].ToString();
                nhanvien.DCNV = form["DCNV"].ToString();
                nhanvien.DTNV = form["DTNV"].ToString();
                nhanvien.MAPB = form["MAPB"].ToString();
                //nhanvien.CHUCDANH = form["CHUCDANH"];
                //nhanvien.CHUCVU = form["CHUCVU"];
                nhanvien.Username = form["Username"].ToString();
                nhanvien.Password = form["Password"].ToString();
                nhanvien.Roles = "Vanthu";
                
                nhanvien.Quyen = Convert.ToInt32(form["Quyen"]);
                
                if (nhanvien.Quyen == 1)
                {
                    nhanvien.CHUCDANH = "Quản trị";
                }
                else if (nhanvien.Quyen == 2)
                {
                    nhanvien.CHUCDANH = "Lãnh đạo";
                }
                else if (nhanvien.Quyen == 3)
                {
                    nhanvien.CHUCDANH = "Chuyên viên";
                }
                else
                {
                    nhanvien.CHUCDANH = "Văn thư";
                }
                db.NVs.Add(nhanvien);
                db.SaveChanges();
                
                return RedirectToAction("Index");
            }
            
            return View(nhanvien);
        }
        #endregion

        #region[Edit]
        public ActionResult Edit(string id)
        {
            NV nv = db.NVs.First(m => m.MSNV == id);
            if (nv == null)
            {
                return HttpNotFound();
            }
            ViewBag.MAPB = new SelectList(db.PHONGBANs, "MAPB", "TENPB", nv.MAPB);
            return View(nv);
        }
        #endregion
        //
        // POST: /NhanVien/Edit/5
        #region[Edit]
        [HttpPost]

        public ActionResult Edit(string id, FormCollection form)
        {
            NV nhanvien = db.NVs.First(pb => pb.MSNV == id);

            string name = ToFirstUpper(form["HOTENNV"]);

            //nhanvien.MSNV = form["MSNV"];
            nhanvien.HOTENNV = name;
            nhanvien.NGAYSINH = form["NGAYSINH"];
            nhanvien.DCNV = form["DCNV"];
            nhanvien.DTNV = form["DTNV"];
            nhanvien.MAPB = form["MAPB"];
            nhanvien.Username = form["Username"];
            nhanvien.Password = form["Password"];
            nhanvien.Roles = form["Roles"];
            if (form["Quyen"] == null)
            {
                nhanvien.Quyen = Convert.ToInt32(4);
            }
            else
                nhanvien.Quyen = Convert.ToInt32(form["Quyen"]);

            if (nhanvien.Quyen ==1 )
            {
                nhanvien.CHUCDANH = "Quản trị";
            }
            if (nhanvien.Quyen == 2)
            {
                nhanvien.CHUCDANH = "Lãnh đạo";
            }
            if (nhanvien.Quyen == 3)
            {
                nhanvien.CHUCDANH = "Chuyên viên";
            }
            if (nhanvien.Quyen == 4)
            {
                nhanvien.CHUCDANH = "Văn thư";
            }
            db.SaveChanges();

            ViewBag.MAPB = new SelectList(db.PHONGBANs, "MAPB", "TENPB", nhanvien.MAPB);

            return RedirectToAction("Index");

        }
        #endregion

        #region[Delete]
        public ActionResult Delete(string id)
        {
            var del_cvden = db.CVDENs.Where(model => model.MSNV == id).ToList();
            var del_cvdi = db.CVDIs.Where(model => model.MSNV == id).ToList();
            var del_ky = db.Kies.Where(model => model.MSNV == id).ToList();

            var del_nv = (from nhanvien in db.NVs where nhanvien.MSNV == id select nhanvien).Single();

            if (del_cvden.Count == 0 && del_cvdi.Count == 0 && del_ky.Count == 0)
            {
                db.NVs.Remove(del_nv);
                db.SaveChanges();

            }
            else
            {
                return View();
            }
            return RedirectToAction("Index");
        }
        #endregion


        //
        // POST: /NhanVien/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            NV nv = db.NVs.Find(id);
            db.NVs.Remove(nv);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }


        #region[MultiDelete]
        public ActionResult MultiDelete()
        {
            foreach (string key in Request.Form)
            {
                var checkbox = "";
                if (key.StartsWith("chk"))
                {
                    checkbox = Request.Form["" + key];
                    if (checkbox != "false")
                    {
                        string id = key.Remove(0, 3);

                        var del_cvden = db.CVDENs.Where(model => model.MSNV == id).ToList();
                        for (int i = 0; i < del_cvden.Count; i++)
                        {
                            db.CVDENs.Remove(del_cvden[i]);
                            db.SaveChanges();
                        }

                        var del_cvdi = db.CVDIs.Where(model => model.MSNV == id).ToList();
                        for (int i = 0; i < del_cvden.Count; i++)
                        {
                            db.CVDIs.Remove(del_cvdi[i]);
                            db.SaveChanges();
                        }

                        var Del = (from emp in db.NVs where emp.MSNV == id select emp).Single();
                        db.NVs.Remove(Del);
                        db.SaveChanges();
                    }
                }
            }
            return RedirectToAction("Index");
        }
        #endregion

        #region[Viết hoa chữ cái đầu các từ và loại bỏ các khoảng trắng thừa ]
        public static string ToFirstUpper(string s)
        {
            if (String.IsNullOrEmpty(s))
                return s;

            string result = "";

            //lấy danh sách các từ  

            string[] words = s.Split(' ');

            foreach (string word in words)
            {
                // từ nào là các khoảng trắng thừa thì bỏ  
                if (word.Trim() != "")
                {
                    if (word.Length > 1)
                        result += word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower() + " ";
                    else
                        result += word.ToUpper() + " ";
                }

            }
            return result.Trim();
        }
        #endregion
    }
}